<template>
  <a-flex justify="space-between">
    <h2>{{ space.spaceName }}（{{ SPACE_TYPE_MAP[space.spaceType] }}）</h2>
    <a-space size="middle">
      <a-button
        type="primary"
        ghost
        :icon="h(TeamOutlined)"
        :href="`/spaceUserManage/${id}`"
        target="_blank"
      >
        成员管理
      </a-button>

      <a-button
        v-if="canUploadPicture"
        type="primary"
        :href="`/add_picture?spaceId=${id}`"
        target="_blank"
      >
        + 创建图片
      </a-button>

      <a-button
        :icon="h(BarChartOutlined)"
        :href="`/space_analyze?spaceId=${id}`"
        target="_blank"
        @click="doBatchEdit"
      >
        空间分析
      </a-button>
      <a-button :icon="h(EditOutlined)" @click="doBatchEdit"> 批量编辑</a-button>
      <a-tooltip :title="`占用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxlSize)}`">
        <a-progress
          type="circle"
          :size="42"
          :percent="((space.totalSize * 100) / space.maxSize).toFixed(1)"
        />
      </a-tooltip>
    </a-space>
  </a-flex>
  <div style="margin-bottom: 16px" />
  <!-- 搜索表单 -->
  <PictureSearchForm :onSearch="onSearch" />
  <div style="margin-bottom: 16px" />

  <!-- 按颜色搜索 -->
  <a-form-item label="按颜色搜索">
    <color-picker format="hex" @pureColorChange="onColorChange" />
  </a-form-item>
  <div style="margin-bottom: 16px" />
  <div id="spaceDetailPage">
    <PictureList :dataList="dataList" :canEdit="canEditPicture" :canDelete="canDeletePicture" :loading="loading" :showOp="true" :onReload="fetchData" />
    <a-pagination
      style="text-align: right"
      v-model:current="searchParams.current"
      v-model:page-size="searchParams.pageSize"
      :total="total"
      @change="onPageChange"
    />
  </div>
  <BatchEditPictureModal
    ref="batchEditPictureModalRef"
    :spaceId="id"
    :pictureList="dataList"
    :onSuccess="onBatchEditPictureSuccess"
  />
</template>
<script setup lang="ts">
import {computed, h, onMounted, ref, watch} from 'vue'
import { useRoute } from 'vue-router'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController'
import { message } from 'ant-design-vue'
import {
  listPictureTagCategoryUsingGet,
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/api/pictureController'
import PictureList from '@/components/PictureList.vue'
import { formatSize } from '@/utils'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import BatchEditPictureModal from '@/components/BatchEditPictureModal.vue'
import { BarChartOutlined, EditOutlined, TeamOutlined } from '@ant-design/icons-vue'
import {SPACE_PERMISSION_ENUM, SPACE_TYPE_MAP} from "../constants/space";

interface props {
  id: string | number
}

const props = defineProps<props>()
const space = ref<API.SpaceVO>({})
const route = useRoute()
// 获取老数据
const fetchSpaceDetail = async () => {
  try {
    // 获取到id
    const res = await getSpaceVoByIdUsingGet({
      id: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    } else {
      message.error('获取空间详细失败.' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取空间详细失败.' + e.message)
  }
}

// 页面加载时加载数据
onMounted(() => {
  fetchSpaceDetail()
})
const loading = ref(true)
// 定义数据
const dataList = ref<API.PictureVO[]>([])
// 搜索条件
const searchParams = ref<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})
const total = ref(0)

// 获取分类标签列表
const selectedCategory = ref<string>('all')
const selectedTag = ref<boolean[]>([])

const categoryList = ref<string[]>([])
const tagList = ref<string[]>([])

/**
 * 获取分类标签选项
 */
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  // 操作成功
  if (res.data.code === 0 && res.data.data) {
    tagList.value = res.data.data.tagList ?? []
    categoryList.value = res.data.data.categoryList ?? []
  } else {
    message.error('获取分类标签失败. ')
  }
}
onMounted(() => {
  getTagCategoryOptions()
})
const fetchData = async () => {
  loading.value = true

  // 转换标签搜索参数
  const params = {
    spaceId: props.id,
    ...searchParams.value,
  }
  const res = await listPictureVoByPageUsingPost(params)

  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败. ' + res.data.message)
  }
  loading.value = false
}
// 分页参数
const onPageChange = (page: number, pageSize: number) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  fetchData()
}

const doSearch = () => {
  // 重置搜索条件
  searchParams.value.current = 1
  fetchData()
}

// 页面加载时加载数据
onMounted(() => {
  fetchData()
})

const onSearch = (newSearchParams: API.PictureQueryRequest) => {
  searchParams.value = {
    ...searchParams.value,
    ...newSearchParams,
    current: 1,
  }
  fetchData()
}

const onColorChange = async (color: string) => {
  loading.value = true
  const res = await searchPictureByColorUsingPost({ picColor: color, spaceId: props.id })

  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data ?? []
    dataList.value = data
    total.value = data.length
  } else {
    message.error('获取数据失败. ' + res.data.message)
  }
  loading.value = false
}

// --------- 批量编辑图片 ---------
const batchEditPictureModalRef = ref()

// 批量编辑成功
const onBatchEditPictureSuccess = () => {
  fetchData()
}

const doBatchEdit = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}
watch(
  () => props.id,
  (newSpaceId) => {
    fetchSpaceDetail()
    fetchData()
  },
)

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (space.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

</script>

<style scoped>
#spaceDetailPage {
  margin-bottom: 16px;
}
</style>
